﻿using BencodeNET.Objects;
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Net;

namespace PrivateTracker.Service.Core;
[Comment("种子peer")]
[Table("tracker_peer")]
public class Peer : DEntityTenant
{
    /// <summary>
    /// 
    /// </summary>
    [ForeignKey("TorrentId")]
    public virtual Torrent torrent { get; set; }
    /// <summary>
    /// 主表外键
    /// </summary>
    [Comment("主表外键")]
    public virtual long TorrentId { get; set; }
    [Comment("客户端标识"), MaxLength(20)]
    public virtual string PeerId { get; set; }
    [Comment("Ip地址"), MaxLength(50)]
    public virtual string Ip { get; set; }
    [Comment("端口")]
    public virtual ushort Port { get; set; }
    [Comment("上传量")]
    public virtual long DownLoaded { get; set; }
    [Comment("下载量")]
    public virtual long Uploaded { get; set; }
    /// <summary>
    /// 客户端
    /// </summary>
    [Comment("客户端"), MaxLength(50)]
    public virtual string Agent { get; set; }
    /// <summary>
    /// 上次活动时间
    /// </summary>
    [Comment("上次活动时间")]
    public DateTimeOffset? PrevActon { get; set; }

    /// <summary>
    /// 最后活动时间
    /// </summary>
    [Comment("最后活动时间")]
    public DateTimeOffset? LastActon { get; set; }
    /// <summary>
    /// 
    /// </summary>
    /// <returns></returns>
    public byte[] ToBytes()
    {
        var portBytes = BitConverter.GetBytes(IPAddress.HostToNetworkOrder((ushort)this.Port));
        var addressBytes = IPAddress.Parse(this.Ip).GetAddressBytes();
        var resultBytes = new byte[portBytes.Length + addressBytes.Length];
        // 根据协议规定，首部的 4 字节为 IP 地址，尾部的 2 自己为端口信息
        Array.Copy(addressBytes, resultBytes, addressBytes.Length);
        Array.Copy(portBytes, 0, resultBytes, addressBytes.Length, portBytes.Length);
        return resultBytes;
    }
    /// <summary>
    /// 
    /// </summary>
    /// <returns></returns>
    public BDictionary ToEncodedDictionary()
    {
        return new BDictionary
            {
                {TrackerConsts.PeerIdKey,new BString(PeerId)},
                {TrackerConsts.Ip,new BString(this.Ip.ToString())},
                {TrackerConsts.Port,new BNumber(this.Port)}
            };
    }
}
